<template>
  <gui-page ref="guiPage" :fullPage="true" :customHeader="true">
    <template v-slot:gHeader>
      <view class="header">
        <image
          class="header-back"
          src="/static/activity/fanhui btn@2x.png"
          mode="aspectFit"
          @click="goBack"
        ></image>
        <text class="header-title">{{ title }}</text>
        <view style="width: 50rpx"></view>
      </view>
    </template>
    <template v-slot:gBody>
      <view class="gui-flex1 gui-flex gui-column">
        <swiper
          :current="currentIndex"
          @change="swiperChange"
          :style="{ height: swiperHeight + 100 + 'px', width: '750rpx' }"
        >
          <swiper-item class="gui-bg-gray">
            <view id="content-wrap1" style="padding: 0 15rpx">
              <view
                class="gui-flex gui-row gui-space-between"
                style="margin-top: 15rpx"
              >
                <view
                  class="gui-waterfall-item"
                  v-for="(lists, index1) in noteList1"
                  :key="index1"
                >
                  <view
                    :id="'waterfall1' + index1 + index2"
                    @tap="goDetail(notes)"
                    class="gui-waterfall-items gui-bg-white gui-border-radius gui-relative"
                    style="overflow: hidden"
                    v-for="(notes, index2) in lists"
                    :key="index2"
                  >
                    <text
                      v-if="notes.noteType === '1' || notes.noteType === 1"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >图文笔记</text
                    >
                    <text
                      v-if="notes.noteType === '2' || notes.noteType === 2"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >视频笔记</text
                    >
                    <text
                      v-if="notes.noteType === '3' || notes.noteType === 3"
                      style="width: 130rpx"
                      class="gui-card-tip gui-border-radius gui-absolute-rt gui-text-small gui-color-white gui-bg-black-opacity5"
                      >文字笔记</text
                    >

                    <gui-image
                      @imgLoad="imgLoad"
                      :src="notes.firstPicture"
                      :width="355"
                      borderRadius="16"
                    ></gui-image>
                    <view class="masking" style="">
                      <text>{{ notes.noteTitle }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view style="padding: 20rpx 0">
              <gui-loadmore
                v-show="currentIndex == 0"
                ref="loadmorecom1"
                :status="1"
              ></gui-loadmore>
            </view>
          </swiper-item>
        </swiper>
      </view>
    </template>
  </gui-page>
</template>

<script>
import graceJS from "@/Grace6/js/grace.js";
import GuiImage from "../../Grace6/components/gui-image.vue";
import GuiPage from "@/Grace6/components/gui-page.vue";
import GuiLoadmore from "@/Grace6/components/gui-loadmore.vue";
import commonMixin from "@/mixin/commonMinxin";

export default {
  mixins: [commonMixin],
  components: {
    GuiLoadmore,
    GuiPage,
    GuiImage,
  },
  data() {
    return {
      loaded: false,
      currentIndex: 0,
      swiperHeight: 0,
      defaultSwiperHeight: 0,
      noteList1: [[], []],
      apiLoadingStatus1: false,
      page1: 1,
      loadMoreTimer1: null,
      title: "宠物日记",
      petId: "", // 宠物ID
    };
  },
  watch: {
    currentIndex(newVal, OldVal) {
      this.$nextTick(() => {
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
  },
  methods: {
    imgLoad() {
      this.$nextTick(() => {
        this.setSwiperHeight(this.currentIndex + 1);
      });
    },
    setSwiperHeight(i) {
      var swiperHeightTimer = null;
      if (swiperHeightTimer != null) {
        clearTimeout(swiperHeightTimer);
      }
      swiperHeightTimer = setTimeout(() => {
        let element = "#content-wrap" + i.toString();
        let query = uni.createSelectorQuery().in(this);
        query.select(element).boundingClientRect();
        query.exec((res) => {
          if (res && res[0]) {
            if (
              res[0].height == 0 ||
              res[0].height < this.defaultSwiperHeight
            ) {
              this.swiperHeight = this.defaultSwiperHeight;
            } else {
              this.swiperHeight = res[0].height;
            }
          }
        });
      }, 100);
    },
    navchange: function (index) {
      this.currentIndex = index;
    },
    swiperChange: function (e) {
      var index = e.detail.current;
      this.currentIndex = index;
    },
    goBack() {
      uni.navigateBack();
    },
    goDetail(e) {
      let checkLogin = uni.app.checkLogin();
      if (checkLogin) {
        const noteType = String(e.noteType);
        if (noteType === "1") {
          uni.navigateTo({
            url: "/pages/notes/detail/detail?noteId=" + e.noteId,
          });
        } else if (noteType === "2") {
          uni.navigateTo({
            url: "/pages/notes/videoDetail/videoDetail?noteId=" + e.noteId,
          });
        } else if (noteType === "3") {
          uni.navigateTo({
            url: "/pages/notes/musicDetail/musicDetail?noteId=" + e.noteId,
          });
        } else {
          console.log("未知笔记类型:", noteType);
        }
      }
    },
    getPetDiaries(isReload) {
      console.log("开始加载宠物日记，第" + this.page1 + "页");
      this.apiLoadingStatus1 = true;
      const that = this;

      let params = {
        authorId: uni.getStorageSync("userId"),
        followId: uni.getStorageSync("userId"),
        petId: Number(this.petId),
        noteCategory: 1,
        limit: 10,
        offset: this.page1,
      };

      if (!isReload) {
        uni.showLoading({
          title: "加载中...",
          mask: false,
        });
      }

      const handleError = (err) => {
        console.error("API请求失败:", err);
        that.apiLoadingStatus1 = false;
        uni.hideLoading();
        if (that.$refs.loadmorecom1) {
          that.$refs.loadmorecom1.stoploadmore();
        }
        uni.showToast({
          title: "加载失败，请重试",
          icon: "none",
        });
        if (isReload) {
          uni.stopPullDownRefresh();
        }
      };

      uni.app.post("/blog/note/getNotes", params, "", "", (res) => {
        uni.hideLoading();

        if (!res) {
          return handleError("返回数据为空");
        }

        if (res.code == 2000) {
          console.log("getPetDiaries当前页" + that.page1);
          console.log("API返回数据:", res.data);

          let notes = [];
          let totalPages = 1;

          if (res.data && res.data.records) {
            notes = res.data.records || [];
            totalPages = res.data.pages || 1;
            console.log("总页数" + totalPages);
          } else if (Array.isArray(res.data)) {
            notes = res.data;
            totalPages = Math.ceil(notes.length / 10) || 1;
            console.log("估计总页数" + totalPages);
          } else {
            console.log("无法识别的数据结构");
            notes = [];
            totalPages = 1;
          }

          console.log("本次获取数据条数:" + (notes ? notes.length : 0));

          if (that.page1 <= totalPages) {
            if (!notes || notes.length === 0) {
              console.log("没有更多数据了");
              that.apiLoadingStatus1 = false;
              this.$refs.loadmorecom1.nomore();
              if (isReload) {
                uni.stopPullDownRefresh();
              }
              return;
            }

            for (var i = 0; i < notes.length; i++) {
              const noteItem = {
                noteId: notes[i].noteId,
                noteType: notes[i].noteType,
                noteTitle: notes[i].noteName,
                firstPicture: notes[i].firstPicture,
                authorId: notes[i].authorId,
                authorName: notes[i].authorName || "",
                authorAvatar: notes[i].authorAvatar || "/static/img/hot.png",
                isUp: notes[i].isUp || false,
                upCount: notes[i].upCount || 0,
              };

              const leftColHeight = that.noteList1[0].reduce(
                (sum, item) => sum + 1,
                0,
              );
              const rightColHeight = that.noteList1[1].reduce(
                (sum, item) => sum + 1,
                0,
              );

              if (leftColHeight <= rightColHeight) {
                that.noteList1[0].push(noteItem);
              } else {
                that.noteList1[1].push(noteItem);
              }
            }

            this.$nextTick(() => {
              this.setSwiperHeight(1);
            });

            that.page1 = that.page1 + 1;

            if (that.page1 > totalPages) {
              console.log("已加载全部数据");
              this.$refs.loadmorecom1.nomore();
            } else {
              console.log("还有更多数据，下一页:" + that.page1);
              this.$refs.loadmorecom1.stoploadmore();
            }

            that.apiLoadingStatus1 = false;
          } else {
            that.apiLoadingStatus1 = false;
            this.$refs.loadmorecom1.nomore();
          }

          if (isReload) {
            uni.stopPullDownRefresh();
          }
        } else {
          handleError(res);
        }
      });
    },
    postDiary() {
      let data = { id: this.petId };
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let d = JSON.stringify(data);
          window.AndroidBridge.petPublishEvent(d);
          break;
        case "ios":
          window.webkit.messageHandlers.petPublishEvent.postMessage(data);
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
  },
  onPullDownRefresh: function () {
    if (this.apiLoadingStatus1) {
      uni.stopPullDownRefresh();
      return;
    }
    this.page1 = 1;
    this.noteList1 = [[], []];
    this.getPetDiaries(true);
  },
  onLoad: function (options) {
    if (options.petId) {
      this.petId = options.petId;
    }
    this.$nextTick(() => {
      this.getPetDiaries();
      this.loaded = true;
    });
  },
  onReachBottom: function () {
    console.log("我到底部了");
    if (this.apiLoadingStatus1) {
      console.log("API正在加载中，忽略触底事件");
      return;
    }

    if (this.loadMoreTimer1 != null) {
      clearTimeout(this.loadMoreTimer1);
    }

    this.loadMoreTimer1 = setTimeout(() => {
      var status = this.$refs.loadmorecom1.loadMoreStatus;
      console.log("loadMoreStatus:", status);

      if (status != 0) {
        console.log("已经在加载中或者没有更多数据了");
        return null;
      }

      this.$refs.loadmorecom1.loading();
      console.log("触发加载更多");

      this.getPetDiaries();
    }, 50);
  },
  mounted: function () {
    var mountedTimer = null;
    if (mountedTimer != null) {
      clearTimeout(mountedTimer);
    }
    mountedTimer = setTimeout(() => {
      graceJS.getRefs("guiPage", this, 0, (ref) => {
        ref.getDomSize("guiPageBody", (e) => {
          this.swiperHeight = e.height - uni.upx2px(110) - 92.8;
          this.defaultSwiperHeight = e.height - uni.upx2px(110);
        });
      });
    }, 100);
  },
};
</script>

<style lang="scss" scoped>
.gui-waterfall-item {
  width: 355rpx;
}

.gui-waterfall-items {
  margin-bottom: 15rpx;
}

.gui-block {
  margin-top: 10rpx;
}

.header {
  height: 88rpx;
  width: 750rpx;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20rpx;

  .header-back {
    width: 50rpx;
    height: 50rpx;
  }

  .header-title {
    height: 88rpx;
    line-height: 88rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    flex: 1;
    text-align: center;
  }
}

.masking {
  position: absolute;
  bottom: 0;
  font-family: PingFang SC-Bold;
  padding: 18rpx;
  width: 100%;
  border-radius: 0 0 16rpx 16rpx;
  color: #ffffff;
  font-weight: bold;
  line-height: 36rpx;
  background-color: rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(3rpx);
  -webkit-backdrop-filter: blur(3rpx);

  .masking-text {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 40rpx;
  }
}
</style>
